const getBlogList = require('../services/getBlogList')
const getBlog = require('../services/getBlog')
const getLoginStatus = require('../services/getLoginStatus')
const getCollectForUser = require('../services/getCollectForUser')
const sequelize = require('../config/sequelize')
const Collect = require('../model/Collect')
const Article = require('../model/Article')
const Reading = require('../model/Reading')
const User = require('../model/User')

module.exports = {
    new: async (ctx, next) => {
        getLoginStatus(ctx)
        try {
            const postData = Object.assign(ctx.request.body)
            const user = (await User.findOne({
                where: {
                    account: ctx.session.currentUser
                }
            })).dataValues
            const newData = Object.assign({}, {
                userId: user.id
            }, postData)
            await Article.upsert(newData)
            const info = {
                statusCode: 1
            }
            ctx.json(info)
        } catch (err) {
            console.warn(err)
            const info = {
                statusCode: 0
            }
            ctx.json(info)
        }
    },

    list: async (ctx, next) => {
        try {
            const {
                page,
                size
            } = ctx.request.query
            let info = await getBlogList(page, size)
            ctx.json(info)
        } catch (err) {
            console.warn(err)
            ctx.json({
                statusCode: 0
            })
        }
    },

    collect: async (ctx, next) => {
        try {
            const {
                page,
                size
            } = ctx.request.query
            const user = (await User.findOne({
                where: {
                    account: ctx.session.currentUser
                }
            })).dataValues
            const detail = await Collect.findAll({
                where: {
                    userId: user.id
                },
                order: [
                    ['id', 'DESC']
                ],
                offset: (page - 1) * size,
                limit: parseInt(size)
            })
            let arr = []
            for (let t of detail) {
                arr.push(t.dataValues)
            }
            const collectList = await getCollectForUser(arr)
            ctx.json(collectList)
        } catch (err) {
            console.warn(err)
            ctx.json({
                statusCode: 0
            })
        }
    },

    getCollectStatus: async (ctx, next) => {
        try {
            const {
                article
            } = ctx.request.body
            const user = (await User.findOne({
                where: {
                    account: ctx.session.currentUser
                }
            })).dataValues
            const info = await Collect.findOne({
                where: {
                    articleId: article,
                    userId: user.id
                }
            })
            if (info !== null) {
                ctx.json({
                    statusCode: 1
                })
            } else {
                ctx.json({
                    statusCode: 0
                })
            }
        } catch (err) {
            console.warn(err)
            ctx.json({
                statusCode: 0
            })
        }
    },

    addCollect: async (ctx, next) => {
        try {
            const {
                article
            } = ctx.request.body
            const userInfo = (await User.findOne({
                where: {
                    account: ctx.session.currentUser
                }
            }))
            if (!userInfo) {
                // 未登录
                ctx.json({
                    statusCode: -1
                })
                return
            }
            const user = userInfo.dataValues
            const detail = await Collect.find({
                where: {
                    articleId: article,
                    userId: user.id
                }
            })
            if (detail != null) {
                // 已收藏
                await detail.destroy()
                ctx.json({
                    statusCode: 2
                })
                return
            }
            await Collect.upsert({
                articleId: article,
                userId: user.id
            })
            ctx.json({
                statusCode: 1
            })
        } catch (err) {
            console.warn(err)
            ctx.json({
                statusCode: 0
            })
        }
    },

    rank: async (ctx, next) => {
        try {
            let
                page = 1,
                size = 5,
                list = await Article.findAll({
                    order: [
                        ['total_read', 'DESC']
                    ],
                    offset: (page - 1) * size,
                    limit: parseInt(size)
                }),
                statusMsg = [],
                statusCode = 1;
            for (let item of list) {
                statusMsg.push(item.dataValues)
            }
            const info = {
                statusCode,
                statusMsg
            }
            ctx.json(info)
        } catch (err) {
            console.warn(err)
            ctx.json({
                statusCode: 0
            })
        }
    },

    article: async (ctx, next) => {
        try {
            const {
                articleId
            } = ctx.request.body
            const blog = await getBlog(articleId)
            const article = await Article.findAll({
                where: {
                    articleId
                }
            })
            if (ctx.session.currentUser && ctx.session.currentUser != article.userId) {}
            ctx.json(blog)
        } catch (err) {
            console.warn(err)
            ctx.json({
                statusCode: 0
            })
        }
    },

    userArticle: async (ctx, next) => {
        try {
            const user = (await User.findOne({
                where: {
                    account: ctx.session.currentUser
                }
            })).dataValues
            const articleList = (await Article.findAll({
                where: {
                    userId: user.userId
                }
            }))
            const info = {
                statusCode: 1,
                statusMsg: articleList
            }
            ctx.json(info)
        } catch (err) {
            console.warn(err)
            ctx.json({
                statusCode: 0
            })
        }
    },

    articleUpdate: async (ctx, next) => {
        getLoginStatus(ctx)
        try {
            const postData = ctx.request.body
            const id = postData.id
            const {
                content,
                shortContent,
                kind,
                title
            } = postData
            await Article.update({
                content,
                shortContent,
                kind,
                title
            }, {
                where: {
                    id: id
                }
            })
            ctx.json({
                statusCode: 1
            })
        } catch (err) {
            console.warn(err)
            ctx.json({
                statusCode: 0
            })
        }
    },

    delete: async (ctx, next) => {
        getLoginStatus(ctx)
        const postData = ctx.request.body
        // 如果不存在用户 则返回失败
        if (!postData.id || !ctx.session.currentUser) {
            ctx.json({
                statusCode: 0
            })
            return
        }
        const id = postData.id
        const article = await Article.findOne({
            where: {
                articleId: postData.id
            }
        })
        article.destroy()
        const collect = await Collect.findAll({
            where: {
                articleId: postData.id
            }
        })
        for(let item of collect) {
            item.destroy()
        }
        ctx.json({
            statusCode: 1
        })
    }
}